// http 请求拦截器
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders, HttpHeaderResponse, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { from, Observable, of } from 'rxjs';
import { mergeMap, catchError } from 'rxjs/operators';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router } from '@angular/router';


@Injectable()
export class DefaultInterceptor implements HttpInterceptor {
    private timeout = 1000 * 30; // 30s超时
    private timer = 0;
    constructor(private message: NzMessageService, private router: Router) {
    }

    //Observable<| HttpHeaderResponse | HttpResponse<any>>
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        //这里可以在请求中加参数
        let req = request.clone();
        return next.handle(req).pipe(mergeMap((event: any) => {
            // 正常返回，处理具体返回参数
            if (event instanceof HttpResponse && (event.status === 200 || event.status === 201)) {
                //具体处理请求返回数据
                return this.handleData(event);
            } else {
                return of(false);
            }
        }),
            catchError((err: HttpErrorResponse) => this.handleData(err)))
    }

    private handleData(
        event: HttpResponse<any> | HttpErrorResponse,
    ): Observable<any> {
        // 业务处理：一些通用操作
        switch (event.status) {
            case 0: 
                this.message.create('error', '服务未开启！');
                break;
            case 200:
            case 201:
                if (event instanceof HttpResponse) {
                    const body: any = event.body;
                    if (body && body.code == 0) {
                        return of(event);
                    }
                }
                break;
            // 未登录状态码
            case 401: 
                this.message.create('error', event['error']['data']);
                this.router.navigate(['/login']);
                break;
            case 404:
                this.message.create('error', '404');
                break;
            case 500:
                this.message.create('error', '500');
                break;
            default:
                this.message.create('error', '未知错误，请联系管理员！');
        }
        return of(false);

    }
}
